package com.sunlei.webtest.quickstart.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: sun
 * @Description: 学习rabbitmq return listener机制
 * @Data: create in 15:42 2018/11/23
 * @Modfied by:
 */
public class Producter {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel  = connection.createChannel();
        final String exchangeName = "test_return_exchange";
        final String routeKey1 = "return.save";
        final String routeKey2 = "notFind.save";
        channel.basicPublish(exchangeName,routeKey1,true,null,"test return 1".getBytes());
        channel.basicPublish(exchangeName,routeKey2,true,null,"test return 2".getBytes());

        /**添加return listener
         * 需要实现ReturnListener()接口
         * */
        channel.addReturnListener(new ReturnListener() {
            /**
             * @param replyCode :响应码
             * @param replyText :响应文本
             * */
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("[return listener]:");
                System.out.println("    replyCode:"+replyCode);
                System.out.println("    replyText:"+replyText);
                System.out.println("    exchange:"+exchange);
                System.out.println("    routeKey:"+routingKey);
                System.out.println("    body:"+new String(body));
            }
        });
    }
}
